import {Row, Col, Modal, Button, Icon, message, Table, Dropdown, Menu, Form} from 'antd';
// import Row from '../../../_antd1.11.2/Row';
// import Col from '../../../_antd1.11.2/Col';
// import Modal from '../../../_antd1.11.2/Modal';
// import Button from '../../../_antd1.11.2/Button';
// import Icon from '../../../_antd1.11.2/Icon';
// import message from '../../../_antd1.11.2/message'
// import Table from '../../../_antd1.11.2/table';
// import Dropdown from '../../../_antd1.11.2/dropdown';
// import Menu from '../../../_antd1.11.2/menu';
// import Form from '../../../_antd1.11.2/form';
//import {Row,Col,Modal,Button,Icon,message,Table,Dropdown,Menu,Form} from 'antd'
//import {WeaTools,WeaScroll,WeaSelect,WeaBrowser,WeaScope,WeaSelectGroup,WeaAssociativeSearch} from 'ecCom'
const MenuItem = Menu.Item;
const FormItem = Form.Item;

import WeaTools from '../../wea-tools';
import WeaScroll from '../../wea-scroll';
import WeaSelect from '../../wea-select';
import WeaBrowser from '../../wea-browser';
import WeaScope from '../../wea-scope';
import WeaSelectGroup from '../../wea-select-group';
import WeaAssociativeSearchMult from '../wea-associative-search-mult';

import isEqual from 'lodash/isEqual';
import objectAssign from 'object-assign'

//国际化 zxt- 20170419
const defaultLocale = {
  	total: '共',
  	totalUnit: '条',
  	operates: '操作',
  	delete: '删除',
  	customColSave: '保存',
  	customColCancel: '取消',
};


class Main extends React.Component {
	//国际化 zxt- 20170419
	static contextTypes = {
	    antLocale: React.PropTypes.object,
	}
	getLocale() {
	    let locale = {};
	    if (this.context.antLocale && this.context.antLocale.Table) {
	    	locale = this.context.antLocale.WeaTable;
	    }
	    return { ...defaultLocale, ...locale, ...this.props.locale };
  	}
    constructor(props) {
        super(props);
        this.state = {
        	conditions: [],
        	labels: {},
        	//table
        	columns: [],
        	datas: this.addKeytoDatas(props.replaceDatas) || [],
        	selectedRowKeys: [],
        	pageSize: 10,
        	//select
        	selectDatas: {},
        	//modal
        	visible: false,
        	_visible: false,
        	addData: {},
        	addDataInit: {},
        	seclevelMin:0,
        	seclevelMax:100
        }
        this.onBrowerChange = this.onBrowerChange.bind(this);
        this.onBrowerClick = this.onBrowerClick.bind(this);
        this.onOk = this.onOk.bind(this);
        this.onCancel = this.onCancel.bind(this);
        this.onClear = this.onClear.bind(this);
        this._onOk = this._onOk.bind(this);
        this._onCancel = this._onCancel.bind(this);
		this.doAdd = this.doAdd.bind(this);
    }
    componentDidMount() {
	    const { replaceDatas = [] } = this.props;
    	//this.getDates();
		let { conditionURL = '' } = this.props;
		//初始化数据
    	WeaTools.callApi(conditionURL).then(datas => {
    		const { conditions, columns, labels } = datas;
    		const addData = { sharetype: conditions[0].options[0].key, sharetypespan: conditions[0].options[0].showname };
    		this.setState({ conditions, columns, labels, addData, addDataInit: addData });
	    	let _datas = this.addKeytoDatas(replaceDatas);
	      	this.setState({ datas: _datas, selectDatas: this.getSelectDatas(_datas) });
    	});
    }

    render() {
    	const { inputStyle = {}, type = '141', modalStyle = {} } = this.props;
    	const { datas, selectDatas, visible, _visible, selectedRowKeys } = this.state;
        const buttons = [
            <Button key="submit" type="primary" size="large" onClick={this.onOk} disabled={false}>确 定</Button>,
            <Button key="clear" type="ghost" size="large" onClick={this.onClear}>清 除</Button>,
            <Button key="back" type="ghost" size="large" onClick={this.onCancel}>取 消</Button>
       	];
       	const _buttons = [
            <Button key="submit" type="primary" size="large" onClick={this._onOk} >保 存</Button>,
            <Button key="back" type="ghost" size="large" onClick={this._onCancel}>取 消</Button>
       	];
        return (
          	<div className='wea-hrm-condition'>
            	<WeaAssociativeSearchMult
	                {...this.props}
	                style={ inputStyle }
	                datas={ selectDatas }
	                selectedValues={this.getSelectKeys()}
	                isClearData={JSON.stringify(selectDatas) === '{}'}
	                type={type}
	                clickCallback={this.onBrowerClick}
	                onChange={this.onBrowerChange}

	            />
            	<Modal wrapClassName="wea-hr-muti-input"
		            title={this.getTitle()}
		            width={modalStyle.width}
		            maskClosable={false}
		            visible={visible}
		            onCancel={this.onCancel}
		            footer={buttons}
		        >
		            <div className='wea-table-edit wea-hrm-condition-table' style={{height: 460}}>
		            	<Row className="wea-table-edit-title" >
							<Col>
								{ '已添加条件' }
								<Button type="primary" disabled={!`${selectedRowKeys}`} title='删除' size="small" onClick={this.doDelete.bind(this,selectedRowKeys)} ><Icon type="minus" /></Button>
								<Button type="primary"  title='新增' size="small" onClick={this.doAdd}><Icon type="plus" /></Button>
							</Col>
			            </Row>
                        <Table
		                	columns={this.getColumns()}
		                	dataSource={datas}
		                	pagination={this.getPagination()}
		                	rowSelection={this.getRowSelection()}
		                	scroll={{ y: 372 }}
		                />
		            </div>
		            <Modal wrapClassName="wea-hr-muti-input"
			            title={this.getTitle(true)}
			            width={modalStyle.width * 0.6}
			            maskClosable={false}
			            visible={_visible}
			            onCancel={this._onCancel}
			            footer={_buttons}
			        >
			            {this.getAddComponent()}
		            </Modal>
	            </Modal>
          	</div>
        );
    }
    //添加条件
    doAddComponentChange(type, key, value, list, url){
    	const { addData, conditions } = this.state;
    	let _addData = key === 'sharetype' ?  this.shareTypeChangeGetInitData(value) : objectAssign({},addData);
    	let _value  = value == undefined ? '' : value;
    	if(type === 'BROWSER') {
			_addData[key] = _value;
			_addData[`${key}data`] = list;
			_addData[`${key}url`] = url;
    	}else if(type === 'SELECT') {
    		_addData[key] = _value;
    		list.map(l => {
				if(l.key === _value){
					_addData[`${key}span`] = l.showname;
					if(url)	_addData[`${key}url`] = `${url}${_value}`;
				}
			})
	    } else if(type === 'INPUT_INTERVAL'){
	    	_addData[key][0] = _value ;
	    	_addData[key][1] = list == undefined ? '':list ;
	    }
	    this.setState({addData:_addData})
    }

    shareTypeChangeGetInitData(sharetype){
    	const {seclevelMin,seclevelMax,conditions} = this.state;
    	let _addData = {};
    	if(sharetype === '2'){
    		_addData.seclevel = [seclevelMin,seclevelMax];
    	}else if(sharetype === '3'){
    		_addData.seclevel = [seclevelMin,seclevelMax];
    	}else if(sharetype === '4'){
    		_addData.seclevel = [seclevelMin,seclevelMax];
    		const option0 = conditions[1][sharetype][1].options[0];
    		_addData.rolelevel =  option0.key;
    		_addData.rolelevelspan =  option0.showname;
    	}else if(sharetype === '5'){
    		_addData.seclevel = [seclevelMin,seclevelMax];
    	}else if(sharetype === '6'){
    		const option0 = conditions[1][sharetype][1].options.filter(o=> o.selected);
    		_addData.joblevel =  option0[0].key;
    		_addData.joblevelspan =option0[0].showname;
    	}
    	return _addData;
    }

    getAddComponent(){
    	const { conditions, addData,seclevelMin,seclevelMax } = this.state;
    	if(!`${conditions}`) return null;
    	const index = addData.sharetype;
    	return (
    		<div style={{ padding: 20 }}>
    			<FormItem
                    label={conditions[0].label}
                    labelCol={{span: conditions[0].labelcol}}
                    wrapperCol={{span: conditions[0].fieldcol}}>
                        <WeaSelect
                        	value={index}
    						onChange={v => this.doAddComponentChange('SELECT',conditions[0].domkey[0],v,conditions[0].options)}
		                    options= {conditions[0].options}
		                />
                </FormItem>
				{
					conditions[1][index].map(condition => {
						let showDropMenu = false;
						let replaceDatas = [];
						let startValue = seclevelMin;
						let endValue = seclevelMax;
						if(condition.conditionType === 'BROWSER') {
							if(condition.browserConditionParam)
								showDropMenu = condition.browserConditionParam.type=='4' || condition.browserConditionParam.type=='164';//部门分部显示维度菜单
								replaceDatas = addData[`${condition.domkey[0]}data`]||[];
						}
						if(condition.conditionType === 'INPUT_INTERVAL' && addData[condition.domkey[0]]){
							const value = addData[condition.domkey[0]];
							startValue = Number(value[0]);
							endValue = Number(value[1]);
						}
						return (
							<FormItem
			                    label={condition.label}
			                    labelCol={{span: condition.labelcol}}
			                    wrapperCol={{span: condition.fieldcol}}>
			    					{
			    						condition.conditionType === 'SELECT' &&
				    					<WeaSelect
				    						value={addData[condition.domkey[0]] || '1'}
				    						onChange={v => this.doAddComponentChange('SELECT',condition.domkey[0],v,condition.options)}
						                    options= {condition.options}
						                />
			    					}
			    					{
			    						condition.conditionType === 'BROWSER' &&
			    						<WeaBrowser {...condition.browserConditionParam}
			    							viewAttr={3}
			    							replaceDatas={replaceDatas}
			    							showDropMenu={showDropMenu}
			    							onChange={(v, name, list) => this.doAddComponentChange('BROWSER',condition.domkey[0],v,list,condition.browserConditionParam.linkUrl)}
			    						/>

			    					}
			    					{
			    						condition.conditionType === 'INPUT_INTERVAL' &&
			    						<WeaScope
			    							min={[seclevelMin,seclevelMax]}
			    							max={[seclevelMin,seclevelMax]}
			    							domkey={condition.domkey}
			    							startValue={startValue}
			    							endValue={endValue}
			    							onChange={(start, end) => this.doAddComponentChange('INPUT_INTERVAL',condition.domkey[0],start,end)}
			    						/>
			    					}
			    					{
			    						condition.conditionType === 'SELECT_LINKAGE' &&
			    						<WeaSelectGroup
			    							domkey={condition.domkey}
			    							options={condition.options}
			    							selectLinkageDatas={condition.selectLinkageDatas}
			    							onChange={(v, b) => {
			    								this.doAddComponentChange('SELECT',condition.domkey[0],v,condition.options);
			    								b && b.length && b.length > 0 && this.doAddComponentChange('BROWSER',condition.domkey[1],b[0],b[2],condition.selectLinkageDatas[v].browserConditionParam.linkUrl)
			    							}}
			    						/>
			    					}
			                </FormItem>
						)
					})
				}
			</div>
    	)
    }
    //util
    getDates(){
		let { conditionURL = '' } = this.props;
    	WeaTools.callApi(conditionURL).then(datas => {
    		const { conditions, columns, labels } = datas;
    		const addData = { sharetype: conditions[0].options[0].key, sharetypespan: conditions[0].options[0].showname };
    		this.setState({ conditions, columns, labels, addData, addDataInit: addData });
    	})
    }
    addKeytoDatas(datas){
		let _datas = datas.map((data, i) => {
			let _data = {...data};
			_data.key = i
			return _data
		})
		return _datas
	}
    getSelectDatas(datas){
    	let { labels } = this.state;
    	let selectDatas = {};
    	datas.map(data => {
    		const {
    			key,
    			sharetype, sharetypespan,
    			relatedshare, relatedsharespan, relatedshareurl,
    			rolelevel, rolelevelspan, rolelevelurl,
    			joblevel, joblevelspan, joblevelurl,
    			jobfield, jobfieldspan, jobfieldurl,
    			seclevel, seclevelspan,
    		} = data;
    		let name = null;

    		let _relatedsharespan = relatedshareurl ?
							    		(sharetype === '1' ?
							    			`<span class='condition-item-a' onClick='window.resourceConditionOpenHrm(${relatedshare})'>${relatedsharespan}</span>`
							    			:
							    			`<span class='condition-item-a' onClick="window.resourceConditionOpenTab('${relatedshareurl}')" >${relatedsharespan}</span>`
							    		)
							    		:
							    		relatedsharespan;
    		if(relatedshare !== undefined) {
    			name = `<span>${sharetypespan}(${_relatedsharespan})</span>`;
    		}

    		if(rolelevel !== undefined) {
    			let _rolelevel = rolelevelurl ? `<span class='condition-item-a' onClick="window.resourceConditionOpenTab('${rolelevelurl}')" >${labels.rolelevelprefix || ''}${rolelevelspan}</span> ` : `${labels.rolelevelprefix || ''}${rolelevelspan}`;
    			name =`<span>${sharetypespan}(${_relatedsharespan})${_rolelevel}&nbsp;</span>`;
    		}
			if(joblevel !== undefined) {
    			let _jobfield = '';
    			let _jobfieldspan = '';
    			if(jobfield !== undefined){
    				_jobfield = jobfield.split(',');
    				_jobfieldspan = jobfieldspan.split(',');
    			}
    			let _jobfieldhtml  = '';
    			if(jobfield !== undefined){
    				_jobfieldhtml += `<span>(`;
    				_jobfield.map((_jobf, i) => {
    					if(i > 0){
    						_jobfieldhtml+="&nbsp;&nbsp;";
    					}
    					if(jobfieldurl){
    						_jobfieldhtml+=`<span class='condition-item-a' onClick="window.resourceConditionOpenTab('${jobfieldurl + _jobf}')" >${_jobfieldspan[i]}</span>`;
    					}else{
    						_jobfieldhtml+=_jobfieldspan[i];
    					}
    				});
    				_jobfieldhtml+=`)</span>`;
    			}
    			name = `<span>${sharetypespan}(${_relatedsharespan}/${joblevelspan}${_jobfieldhtml})</span>`;
			}
			let _seclevel = '';
			if(seclevel !== undefined){
				_seclevel = labels[`seclevellabel${sharetype}`] ? labels[`seclevellabel${sharetype}`].replace('{$level$}',seclevel) : seclevel
			}

			if(sharetype === '5') {
				name = '';
			}
    		selectDatas[key] = {
    			id: key,
    			name:`<span>${name}${_seclevel}</span>`
    		}
    	});
    	return selectDatas;
    }
    //select
    getSelectKeys(){
    	const { selectDatas } = this.state;
    	let selectKeys = [];
    	for(key in selectDatas){
    		selectKeys.push(key);
    	}
    	return selectKeys
    }
    onBrowerClick(){
    	this.setState({visible: true});
    	const {datas} = this.state;
    	if(datas && datas.length === 0){
    		this.doAdd();
    	}
    }
    onBrowerChange(values, selectDatas){
    	try{
	    	const { datas } = this.state;
	    	let _datas = datas.filter(data=>{
	    		return this.arrContains(values,data.key);
	    	});
	    	this.setState({
	    		datas: _datas,
	    		selectDatas: selectDatas
	    	});
	    	this.props.onChange('', '', _datas);
    	}catch(e){console.log(e)}

    }
    //table
    getColumns(){
    	const { columns, conditions } = this.state;
		let _columns = [].concat(columns);
		_columns = _columns.map(col => {
			col.width = col.oldWidth;
			let _col = { ...col };
			if(_col.dataIndex === 'sharetype'){
				_col.render = ( text, record, index ) => {
					return record.sharetypespan
				}
			}
			if(_col.dataIndex === 'condition'){
				_col.render = ( text, record, index ) => {
					let textArr = [];
					if(record.relatedsharespan !== undefined){
						textArr.push(record.relatedsharespan);
					}
					if(record.joblevelspan !== undefined){
						textArr.push(record.joblevelspan);
					}
					if(record.rolelevelspan !== undefined){
						textArr.push(record.rolelevelspan);
					}
					let newText = textArr.join(' /');
					if(record.jobfieldspan !== undefined){
						newText += `(${record.jobfieldspan})`;
					}
					return newText
				}
			}
			return _col
		});
		const locale = this.getLocale();
		_columns.push({
			title: '',
			dataIndex: 'ops',
			key: 'ops',
			width: '15%',
            className:"wea-table-operates",
            render: ( text, record, index )=> {
            	const menu = (
            		<Menu>
                        <MenuItem>
	                        <a href='javascript:void(0);' onClick={this.doDelete.bind(this,[record.key])}>{locale.delete}</a>
	                    </MenuItem>
                    </Menu>
            	)
            	return (
                    <div className='wea-hrm-condition-table-ops'>
                        <Dropdown overlay={menu}>
                            <span>
                                {locale.operates} <Icon type="caret-down" />
                            </span>
                        </Dropdown>
                    </div>
                )
            }
		});
		return _columns
    }
    getPagination() {
		return false
	}
    getRowSelection(){
		const { columns, selectedRowKeys } = this.state;
		if(!`${columns}`) return null
		const rowSelection = {
			selectedRowKeys,
			onChange: (sRowKeys, selectedRows) => {
				this.setState({selectedRowKeys : sRowKeys});
			}
		}
		return rowSelection
	}
    //btns
    doAdd(){
    	this.setState({_visible: true})
    }
    doDelete(keys){
    	const { datas } = this.state;
    	let _datas = [].concat(datas);
    	keys.map(key => {
    		_datas = _datas.filter(_data => _data.key !== key)
    	});
    	_datas = this.addKeytoDatas(_datas);
    	this.setState({
    		datas: _datas,
    		selectedRowKeys: []
    	});
    }
    //modal
    getTitle(bool){
    	const { icon = '', title = '人力资源条件', iconBgcolor = ''} = this.props;
    	return (
    		<Row>
                <Col span="8" style={{ paddingLeft:20, lineHeight:'48px' }}>
                    <div className="wea-hr-muti-input-title">
                        {iconBgcolor ? <div className="wea-workflow-radio-icon-circle" style={{background:iconBgcolor ? iconBgcolor : ""}}><i className={icon}/></div>
                        : <span style={{verticalAlign:'middle',marginRight:10}}><i className={icon}/></span>}
                        <span style={{verticalAlign:'middle'}}>{ bool ? '添加条件' : title}</span>
                    </div>
                </Col>
            </Row>
    	)
    }
    onOk(){
    	const { datas } = this.state;
    	this.setState({visible: false,selectDatas: this.getSelectDatas(datas)});
    	if(typeof this.props.onChange === 'function'){
	    	let _datas = datas.map((data, i) => {
				let _data = {...data}
				delete _data.key
				return _data
			});
	    	this.props.onChange('', '', _datas);
    	}
    }
    onClear(){
    	this.setState({
    		datas: [],
    		selectedRowKeys: [],
    		selectDatas:[],
    		visible: false
    	})
    	this.props.onChange('', '', []);
    }
    onCancel(){
    	const { replaceDatas = [] } = this.props;
    	this.setState({
    		datas: this.addKeytoDatas(replaceDatas),
    		selectDatas: this.getSelectDatas(this.addKeytoDatas(replaceDatas)),
    		selectedRowKeys: [],
    		visible: false,
    	})
    }
    _onOk(){
    	const { datas, addData, addDataInit } = this.state;
    	let _datas = [].concat(datas);
    	let _addDatas  = [];
    	const { sharetype,sharetypespan,
    			relatedshareurl='',relatedsharedata=[],
    			joblevel,joblevelspan,
    			jobfield,jobfielddata=[],jobfieldurl='',
    			seclevel=[],
    			rolelevel,rolelevelspan} = addData;
    	let jobfieldspan = [];
    	if(jobfielddata.length > 0){
    		jobfielddata.map((o)=>jobfieldspan.push(o.name));
    	}
    	const isRequired  = this.checkRequire(sharetype,relatedsharedata,jobfielddata,joblevel,seclevel);
    	if(isRequired){
			 relatedsharedata.map((o,i)=>{
			 	let item = {
			 		sharetype:sharetype,
			 		sharetypespan:sharetypespan,
			 		relatedshare:o.id,
			 		relatedsharespan:o.name||o.lastname||'',
			 		relatedshareurl:relatedshareurl
			 	};
			 	if(seclevel.length === 2) item.seclevel  = seclevel.join('-');
			 	if(joblevel) {
			 	 	item.joblevel  = joblevel;
			 	 	item.joblevelspan = joblevelspan;
			 	}
			 	if(rolelevel){
			 		item.rolelevel  = rolelevel;
			 		item.rolelevelspan =  rolelevelspan;
			 	}
			 	if(jobfielddata.length > 0){
			 		item.jobfieldspan = jobfieldspan.join(',');
			 		item.jobfieldurl  = jobfieldurl;
			 		item.jobfield = jobfield;
			 	}
			 	_addDatas.push(item);
			 });
			 //所有人
			 if(sharetype === "5"){
			 	_addDatas.push({sharetype:sharetype,sharetypespan:sharetypespan,seclevel:seclevel.join('-')});
			 }
			 _datas = this.addKeytoDatas(_datas.concat(_addDatas))
    		this.setState({
    			_visible: false,
    			datas: _datas,
    			addData: addDataInit,
    		});
    	}
    }
    //验证表单必填
    checkRequire(sharetype,relatedsharedata,jobfielddata,joblevel,seclevel){
    	if((sharetype === '2' || sharetype === '3' || sharetype === '4' || sharetype === '5') && (seclevel.length < 2 || (seclevel.length === 2 && (seclevel[0] === '' || seclevel[1] === '')))){ //所有人
    		message.warning('安全级别不能为空！',5)
    		return false;
    	}

    	if(sharetype === '5'){
    		return true;
    	}

    	if(relatedsharedata.length === 0){
    		message.warning('对象不能为空！',5)
    		return false;
    	}

    	if(sharetype === '6'  && ((joblevel === '0' || joblevel === '1') && jobfielddata.length ===0)){
    		message.warning(joblevel === '0' ? '部门不能为空！':'分部不能为空！',5)
    		return false;
    	}
    	return true;
    }

    _onCancel(){
    	const { addDataInit } = this.state;
    	this.setState({_visible: false, addData: addDataInit})
    }

	arrContains(arr,item){
		let i = arr.length;
		while (i--) {
		    if (arr[i] == item) {
		      return true;
		    }
		}
		return false;
	}
}


window.resourceConditionOpenTab =(url)=>{
	window.open(url);
}

window.resourceConditionOpenHrm =(userid)=>{
	window.pointerXY(window.event);
	window.openhrm(userid);
}

export default Main;